<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="120px" v-show="showSearch">
      <el-form-item label="一级图件类型" prop="mapLevel1Category">
        <el-select v-model="queryParams.mapLevel1Category" placeholder="请选择一级图件类型" clearable @change="changeCategory">
          <el-option v-for="item in chartClassifyOption" :key="item.dictId" :label="item.dictName" :value="item.dictId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="二级图件类型" prop="mapLevel2Category">
        <el-select v-model="queryParams.mapLevel2Category" placeholder="请选择二级图件类型" clearable>
          <el-option v-for="item in chartClassifyOption1" :key="item.dictItemId" :label="item.dictItemName" :value="item.dictItemId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="图件名称" prop="mapTemplateName">
        <el-input v-model="queryParams.mapTemplateName" placeholder="请输入图件名称" clearable />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" @click="handleUpload">
          <svg-icon class-name="upload-icon" icon-class="upload" /><span style="margin-left:10px">上传</span>
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="Delete" @click="batchDelete">批量删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="Delete" @click="batchDownload">批量下载</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" tooltip-effect="light" :data="dataList" stripe @selection-change="handleSelectionChange" row-key="dmtId" ref="tableRef">
      <el-table-column type="selection" width="55" align="center" :reserve-selection="true" />
      <el-table-column label="图件名称" align="center" prop="mapTemplateName">
        <template #default="scope">
                    <el-button type="text" @click="handleView(scope.row)">{{ scope.row.mapTemplateName }}</el-button>
                </template>
      </el-table-column>
      <el-table-column label="图件类型" align="center" prop="type" show-overflow-tooltip>
        <template #default="scope">
            <span>{{ scope.row.mapLevel1Category}}</span><br>
            <span>{{ scope.row.mapLevel2Category}}</span>
        </template>
      </el-table-column>
      <el-table-column label="图件描述" align="center" prop="mapTemplateDesc">
        <template #default="{row}">
          <el-popover placement="right" :width="400" trigger="click" v-if="row.mapTemplateDesc">
            <template #reference>
              <el-button type="text">查看</el-button>
            </template>
            <el-card shadow="never">
              <template #header>
                <div class="card-header">
                  <span>图件描述</span>
                </div>
              </template>
              <div v-html="mapDescHtml(row.mapTemplateDesc)"></div>
            </el-card>
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="上传人" align="center" prop="uploadUserName" />
      <el-table-column label="上传日期" align="center" prop="uploadTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="{row}">
          <el-button type="text" @click="handleDown(row.attachmentId)">下载</el-button>
          <el-button type="text" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.page" v-model:limit="queryParams.rows"
      @pagination="getList" />

    <!-- 图件模板上传 -->
    <el-dialog title="图件模板上传" v-model="open" width="600px" append-to-body @close="close">
      <el-form ref="mapRef" :model="mapForm" :rules="mapRules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="图件类型" prop="mapClassify">
                <el-form-item label-width="0px" prop="mapLevel1Category">
                    <el-select v-model="mapForm.mapLevel1Category" placeholder="请选择一级图件类型" @change="changeLevel1" style="width:200px"
                        clearable :disabled="viewFlag">
                        <el-option v-for="item in chartClassifyOption" :key="item.dictId" :label="item.dictName"
                            :value="item.dictId">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label-width="0px" prop="mapLevel2Category" style="margin-left: 40px;">
                    <el-select v-model="mapForm.mapLevel2Category" placeholder="请选择二级图件类型" @change="changeLevel2" style="width:200px"
                        clearable :disabled="viewFlag">
                        <el-option v-for="item in chartClassifyOption2" :key="item.dictItemId"
                            :label="item.dictItemName" :value="item.dictItemId">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="图件上传" prop="attachmentId">
            <FileUpload ref="fileUpload" :fileType="['ult']" v-model="fileList" :limit='1' @beforeUpload="beforeUpload" @uploadFile="uploadFile" :disabled="viewFlag"></FileUpload>
        </el-form-item>
        <el-form-item label="图件名称" prop="mapTemplateName">
          <el-input v-model="mapForm.mapTemplateName" placeholder="请输入图件名称" :disabled="viewFlag"/>
        </el-form-item>
        <el-form-item label="图件描述" prop="mapTemplateDesc">
          <el-input v-model="mapForm.mapTemplateDesc" :autosize="{ minRows: 4 }" maxlength="100" show-word-limit type="textarea" placeholder="请输入图件描述" :disabled="viewFlag"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" v-if="!viewFlag">保存</el-button>
          <el-button @click="close">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="templateModule">
import { getPage, delList, uploadSave, getView, updateSave } from '@/api/resultManage/templateModule.js';
import {  getDictByDictDirId, getDictItemsByDictId } from "@/api/resultManage/chartManger";

const data = reactive({
  queryParams: {
    mapLevel1Category: '',
    mapLevel2Category:'',
    mapTemplateName: '',
    page: 1,
    rows: 10
  },
  total: 0,
  dataList: [],
  mapForm: {},
  fileList: []
})
const { queryParams, total, dataList, mapForm, fileList } = toRefs(data)
const showSearch = ref(true)
const open = ref(false)
const loading = ref(false)
const chartClassifyOption = ref([]);
const chartClassifyOption1 = ref([]);
const chartClassifyOption2 = ref([]);
const mapRules = reactive({
  mapClassify: [{ required: true, trigger: "blur", validator: validatorMapClassify }],
  attachmentId: [{ required: true, message: '请上传图件！', trigger: 'blur' }],
  mapTemplateName: [{ required: true, message: '请填写图件名称！', trigger: 'blur' }]
})
const {proxy} = getCurrentInstance()

//图片分类验证
function validatorMapClassify(rule, value, callback) {
    if (mapForm.value.mapLevel1Category == '' || mapForm.value.mapLevel1Category == undefined) {
        callback(new Error('图件类型不能为空'));
    } else if ((mapForm.value.mapLevel1Category != '' || mapForm.value.mapLevel1Category != undefined) && (mapForm.value.mapLevel2Category == '' || mapForm.value.mapLevel2Category == undefined)) {
        callback(new Error('二级图件类型不能为空'));
    } else if ((mapForm.value.mapLevel1Category != '' || mapForm.value.mapLevel1Category != undefined) && (mapForm.value.mapLevel2Category != '' || mapForm.value.mapLevel2Category != undefined)) {
        callback();
    }
}

const mapDescHtml = (mapDesc) => {
  return mapDesc ? mapDesc.split('').map(item => item =='\n'?'<br>':item).join('') : mapDesc
}

const getList = () => {
  getPage(queryParams.value).then(res => {
    const {code, data} = res
    if(code == 200) {
      dataList.value = data.rows?data.rows:[];
      total.value = data.total;
    }
  })
}

// 一级分类
function getChartClassifyList(){
    getDictByDictDirId().then(res=>{
        chartClassifyOption.value = res.data
    })
}

// 二级分类
function getChartClassifyList2(value){
    getDictItemsByDictId({dictId:value}).then(res=>{
        if(open.value){
            chartClassifyOption2.value = res.data
        }else{
            chartClassifyOption1.value = res.data
        }
    })
}
function changeLevel1(value){
    mapForm.value.mapLevel2Category = '';
    if(value){
        getChartClassifyList2(value);
    }else{
        chartClassifyOption2.value = [];
    }
    proxy.$refs['mapRef'].validateField('mapClassify') 
}
function changeLevel2() {
    proxy.$refs['mapRef'].validateField('mapClassify')
}
function changeCategory(value){
    queryParams.value.mapLevel2Category = '';
    if(value){
        getChartClassifyList2(value);
    }else{
        chartClassifyOption1.value = [];
    }
}
// 查询
const handleQuery = () => {
  getList()
}
// 重置
const resetQuery = () => {
  proxy.resetForm("queryRef");
  queryParams.value.page = 1
  handleQuery();
}
// 上传
const handleUpload = () => {
  open.value = true
}
// 批量删除
const batchDelete = () => {
  if(ids.length == 0){
    proxy.$modal.msgWarning('请至少选择一条数据！')
    return
  }
  proxy.$modal.confirm(`是否确认删除所选数据！`).then(() => {
    delList({dmtIdList: ids})
  }).then(() => {
    proxy.$modal.msgSuccess('删除成功！')
    proxy.$refs['tableRef'].clearSelection();
    queryParams.value.page = 1
    getList()
  })
}
// 批量下载
const batchDownload = () => {
  if(attachIds.length == 0){
    proxy.$modal.msgWarning('请至少选择一条数据！')
    return
  }
  proxy.download("/mapTemplate/download", {attachIdList:attachIds}, '图件模板.zip');
  proxy.$refs['tableRef'].clearSelection();
}
// 下载
const handleDown = (attachId) => {
  location.href = import.meta.env.VITE_APP_BASE_API + "/attachment/downLoadFile?attachId="+ encodeURIComponent(attachId)
}
// 删除
const handleDelete = (row) => {
  proxy.$modal.confirm(`是否确认删除该数据！`).then(() => {
    delList({dmtIdList: [row.dmtId]})
  }).then(() => {
    proxy.$modal.msgSuccess('删除成功！')
    queryParams.value.page = 1
    getList()
  })
}
// 查看
function handleView(row){
  open.value = true;
  viewFlag.value = true;
  getView(row.dmtId).then(res => {
    mapForm.value = res.data;
    getChartClassifyList2(mapForm.value.mapLevel1Category);
    fileList.value = res.data.attachList;
  })
}
// 多选框选中数据
let ids = reactive([])
let attachIds = reactive([])
function handleSelectionChange(selection) {
  ids = selection.map(item => item.dmtId)
  attachIds = selection.map(item => item.attachmentId)
}
// 保存
const submitForm = () => {
  fileList.value = proxy.$refs["fileUpload"].fileList
  mapForm.value.attachmentId = fileList.value.map(item => item.attachId).join(',')
  proxy.$refs.mapRef.validate(valid => {
    if(valid){
      uploadSave(mapForm.value).then(res => {
        if(res.code == 200){
          proxy.$modal.msgSuccess('保存成功！')
          open.value = false
          getList()
        }
      })
    }
  })
}
const close = () => {
  proxy.resetForm('mapRef')
  mapForm.value.attachmentId = ''
  mapForm.value.id = ''
  fileList.value =[];
  open.value = false
  viewFlag.value = false
}
const beforeUpload = (file, cb) => {
  let reg = /[\u4E00-\u9FA5]/g
  if(reg.test(file.name)){
    proxy.$modal.msgError(`上传文件名称不能包含中文!`);
    cb(false)
  }
}
const uploadFile = (attachId) => {
  mapForm.value.attachmentId = attachId
}

const viewFlag = ref(false)

onMounted(() => {
  getChartClassifyList();
  getList()
})

</script>

<style lang="scss">
.el-dialog .el-dialog__body {
  padding: 20px 20px 0;
}
</style>